﻿using AiQiuQuan.Sport.Core;
using AiQiuQuan.Sport.Model.Enums;
using AiQiuQuan.Sport.Model.Models;
using AiQiuQuan.Sport.WebApi.Entities;
using Microsoft.EntityFrameworkCore;

namespace AiQiuQuan.Sport.WebApi.Services.Impl
{
    /// <summary>
    /// private methods
    /// </summary>
    public partial class VenueService
    {
        /// <summary>
        /// 当前用户角色列表
        /// </summary>
        private List<FrameworkUserRoles> GetFrameworkUserRoleList()
        {
            var queryable = from fuserrole in _userRoleRepository.AsNoTracking()
                            join fuser in _frameworkUsersRepository.AsNoTracking()
                            on fuserrole.UserCode equals fuser.ITCode
                            where fuser.ID == _currentInfo.UserId
                            select fuserrole;
            var rolelist = queryable.ToList();
            return rolelist;
        }

        /// <summary>
        /// 提现认证
        /// </summary>
        private async Task<UnaryResult> ValidWithdrawAsync(VenueWithdraw withdraw, FrameworkUsers platformUser, VenueAuditWithdrawRequestDto request)
        {
            if (withdraw == null)
            {
                return UnaryResult.Faild(10, "未查询到提现单");
            }

            if (withdraw.VW_State != WithdrawStateEnum.NoApproved)
            {
                return UnaryResult.Faild(10, "提现单状态不正确，请刷新重试");
            }

            if (platformUser == null)
            {
                return UnaryResult.Faild(10, "未查询到平台用户");
            }

            var user = await _baseUserRepository.AsNoTracking().FirstOrDefaultAsync(m => m.ID == withdraw.UserId.GetValueOrDefault());
            if (user == null)
            {
                return UnaryResult.Faild(10, $"未查询到提现用户信息:{withdraw.UserId}");
            }

            if (request.State == WithdrawStateEnum.Approved)
            {
                if (string.IsNullOrWhiteSpace(user.CardName) || string.IsNullOrWhiteSpace(user.U_WxOpenId))
                {
                    return UnaryResult.Faild(10, $"通知用户进行实名认证，再审核处理:{user.U_Code}");
                }
            }

            return UnaryResult.Succeed();
        }

        /// <summary>
        /// 场馆分页queryable
        /// </summary>
        private IQueryable<VenueInfo> GeneratePageListQueryable(VenuePageRequestDto request)
        {
            var queryable = _venueInfoRepository.AsNoTracking();
            if (request.IsPlatform)
            {
                var rolelist = GetFrameworkUserRoleList();
                if (!rolelist.Any() || (!rolelist.Any(m => m.RoleCode == FrameworkRoleConst.SYS_ADMIN) && !rolelist.Any(m => m.RoleCode == FrameworkRoleConst.VENUE_MANAGE)))
                {
                    queryable = queryable.Where(m => false);
                }
                else if (rolelist.Any(m => m.RoleCode == FrameworkRoleConst.VENUE_MANAGE))
                {
                    queryable = queryable.Where(m => _frameworkUsersRepository.AsNoTracking().Any(j => j.ID == _currentInfo.UserId && j.VenueInfoID == m.ID));
                }
            }

            if (!string.IsNullOrWhiteSpace(request.Name))
            {
                queryable = queryable.Where(m => m.VI_Name.Contains(request.Name));
            }

            if (!string.IsNullOrWhiteSpace(request.PhoneNo))
            {
                queryable = queryable.Where(m => m.Vl_CellNum.Contains(request.PhoneNo));
            }

            if (request.ProvinceId.HasValue)
            {
                queryable = queryable.Where(m => m.ProvinceID == request.ProvinceId.Value);
            }

            if (request.CityId.HasValue)
            {
                queryable = queryable.Where(m => m.CityID == request.CityId.Value);
            }

            return queryable;
        }

        /// <summary>
        /// 教练场馆分页queryable
        /// </summary>
        private IQueryable<VenueInfo> GeneratePageListCoacherQueryable(VenuePageRequestDto request)
        {
            var queryable = from coacherVenue in _coacherVenueRepository.AsNoTracking()
                            join venue in _venueInfoRepository.AsNoTracking()
                            on coacherVenue.VenueId equals venue.ID
                            where coacherVenue.CoacherUserId == _currentInfo.UserId
                            select venue;
            if (!string.IsNullOrWhiteSpace(request.Name))
            {
                queryable = queryable.Where(m => m.VI_Name.Contains(request.Name));
            }

            return queryable;
        }

        /// <summary>
        /// 场地分页queryable
        /// </summary>
        private IQueryable<SiteInfoDto> GenerateSitePageListQueryable(VenueSitePageRequestDto request)
        {
            var queryable = from site in _siteInfoRepository.AsNoTracking()
                            join venue in _venueInfoRepository.AsNoTracking()
                            on site.VenueInfoID equals venue.ID
                            select new SiteInfoDto
                            {
                                ID = site.ID,
                                SiteName = site.SiteName,
                                SiteState = site.SiteState,
                                SiteType = site.SiteType,
                                CreateTime = site.CreateTime,
                                VenueInfoID = site.VenueInfoID,
                                VenueName = venue.VI_Name,
                                ProvinceID = venue.ProvinceID,
                                VI_P_Name = venue.VI_P_Name,
                                CityID = venue.CityID,
                                VI_C_Name = venue.VI_C_Name,
                                Vl_CellNum = venue.Vl_CellNum
                            };
            var rolelist = GetFrameworkUserRoleList();
            if (!rolelist.Any() || (!rolelist.Any(m => m.RoleCode == FrameworkRoleConst.SYS_ADMIN) && !rolelist.Any(m => m.RoleCode == FrameworkRoleConst.VENUE_MANAGE)))
            {
                queryable = queryable.Where(m => false);
            }
            else if (rolelist.Any(m => m.RoleCode == FrameworkRoleConst.VENUE_MANAGE))
            {
                queryable = queryable.Where(m => _frameworkUsersRepository.AsNoTracking().Any(j => j.ID == _currentInfo.UserId && j.VenueInfoID == m.VenueInfoID));
            }

            if (!string.IsNullOrWhiteSpace(request.VenueName))
            {
                queryable = queryable.Where(m => m.VenueName.Contains(request.VenueName));
            }

            if (!string.IsNullOrWhiteSpace(request.PhoneNo))
            {
                queryable = queryable.Where(m => m.Vl_CellNum.Contains(request.PhoneNo));
            }

            if (request.ProvinceId.HasValue)
            {
                queryable = queryable.Where(m => m.ProvinceID == request.ProvinceId.Value);
            }

            if (request.CityId.HasValue)
            {
                queryable = queryable.Where(m => m.CityID == request.CityId.Value);
            }

            return queryable;
        }

        /// <summary>
        /// 场地特殊规则（定期活动）分页queryable
        /// </summary>
        private IQueryable<SitePriceSpecialRuleDto> GenerateSiteSpecialRulePageListQueryable(VenueSitePageRequestDto request)
        {
            var queryable = from siteRule in _sitePriceSpecialRuleRepository.AsNoTracking()
                            join site in _siteInfoRepository.AsNoTracking()
                            on siteRule.SiteInfoID equals site.ID
                            join venue in _venueInfoRepository.AsNoTracking()
                            on siteRule.VenueInfoID equals venue.ID
                            select new SitePriceSpecialRuleDto
                            {
                                ID = site.ID,
                                VenueInfoID = siteRule.VenueInfoID,
                                SPSR_BeginTime = siteRule.SPSR_BeginTime,
                                SPSR_EndTime = siteRule.SPSR_EndTime,
                                SPSR_WeekNum = siteRule.SPSR_WeekNum,
                                SPSR_TimeSlotBegin = siteRule.SPSR_TimeSlotBegin,
                                SPSR_TimeSlotEnd = siteRule.SPSR_TimeSlotEnd,
                                SPSR_IsEffect = siteRule.SPSR_IsEffect,
                                SiteInfoID = siteRule.SiteInfoID,
                                CreateTime = siteRule.CreateTime,
                                SiteName = site.SiteName,
                                VenueName = venue.VI_Name,
                                ProvinceID = venue.ProvinceID,
                                VI_P_Name = venue.VI_P_Name,
                                CityID = venue.CityID,
                                VI_C_Name = venue.VI_C_Name,
                                Vl_CellNum = venue.Vl_CellNum
                            };
            var rolelist = GetFrameworkUserRoleList();
            if (!rolelist.Any() || (!rolelist.Any(m => m.RoleCode == FrameworkRoleConst.SYS_ADMIN) && !rolelist.Any(m => m.RoleCode == FrameworkRoleConst.VENUE_MANAGE)))
            {
                queryable = queryable.Where(m => false);
            }
            else if (rolelist.Any(m => m.RoleCode == FrameworkRoleConst.VENUE_MANAGE))
            {
                queryable = queryable.Where(m => _frameworkUsersRepository.AsNoTracking().Any(j => j.ID == _currentInfo.UserId && j.VenueInfoID == m.VenueInfoID));
            }

            if (!string.IsNullOrWhiteSpace(request.VenueName))
            {
                queryable = queryable.Where(m => m.VenueName.Contains(request.VenueName));
            }

            if (!string.IsNullOrWhiteSpace(request.PhoneNo))
            {
                queryable = queryable.Where(m => m.Vl_CellNum.Contains(request.PhoneNo));
            }

            if (request.ProvinceId.HasValue)
            {
                queryable = queryable.Where(m => m.ProvinceID == request.ProvinceId.Value);
            }

            if (request.CityId.HasValue)
            {
                queryable = queryable.Where(m => m.CityID == request.CityId.Value);
            }

            return queryable;
        }

        /// <summary>
        /// 场地特殊规则（定期活动）列表queryable
        /// </summary>
        private IQueryable<SitePriceSpecialRuleDto> GenerateSiteSpecialRuleListQueryable(Guid siteId)
        {
            var queryable = from special in _sitePriceSpecialRuleRepository.AsNoTracking()
                            join site in _siteInfoRepository.AsNoTracking()
                            on special.SiteInfoID equals site.ID
                            where special.SiteInfoID == siteId
                            select new SitePriceSpecialRuleDto
                            {
                                ID = special.ID,
                                SiteInfoID = special.SiteInfoID,
                                SPSR_BeginTime = special.SPSR_BeginTime,
                                SPSR_EndTime = special.SPSR_EndTime,
                                SPSR_TimeSlotBegin = special.SPSR_TimeSlotBegin,
                                SPSR_TimeSlotEnd = special.SPSR_TimeSlotEnd,
                                SPSR_IsEffect = special.SPSR_IsEffect,
                                SPSR_WeekNum = special.SPSR_WeekNum,
                                VenueInfoID = special.VenueInfoID,
                                Remark = special.Remark,
                                SiteName = site.SiteName,
                                CreateTime = special.CreateTime,
                            };

            return queryable;
        }

        /// <summary>
        /// 场馆退款规则列表queryable
        /// </summary>
        private IQueryable<VenueInfoRefundRuleConfigDto> GenerateRefundRuleListQueryable(Guid venueId)
        {
            var queryable = from rule in _venueInfoRefundRuleConfigRepository.AsNoTracking()
                            join venue in _venueInfoRepository.AsNoTracking()
                            on rule.VenueInfoID equals venue.ID
                            where rule.VenueInfoID == venueId
                            orderby rule.VIRRC_Hours descending
                            select new VenueInfoRefundRuleConfigDto
                            {
                                ID = rule.ID,
                                VenueInfoID = rule.VenueInfoID,
                                VIRRC_Hours = rule.VIRRC_Hours,
                                VIRRC_RefundRatio = rule.VIRRC_RefundRatio,
                                VIRRC_IsEffect = rule.VIRRC_IsEffect,
                                CreateTime = rule.CreateTime,
                                VenueName = venue.VI_Name
                            };
            return queryable;
        }

        /// <summary>
        /// 存在退款规则场馆分页queryable
        /// </summary>
        private IQueryable<VenueInfo> GenerateRefundRuleVenuePageListQueryable(VenuePageRequestDto request)
        {
            var queryable = _venueInfoRepository.AsNoTracking()
                .Where(m => _venueInfoRefundRuleConfigRepository.Any(j => m.ID == j.VenueInfoID));
            var rolelist = GetFrameworkUserRoleList();
            if (!rolelist.Any() || (!rolelist.Any(m => m.RoleCode == FrameworkRoleConst.SYS_ADMIN) && !rolelist.Any(m => m.RoleCode == FrameworkRoleConst.VENUE_MANAGE)))
            {
                queryable = queryable.Where(m => false);
            }
            else if (rolelist.Any(m => m.RoleCode == FrameworkRoleConst.VENUE_MANAGE))
            {
                queryable = queryable.Where(m => _frameworkUsersRepository.AsNoTracking().Any(j => j.ID == _currentInfo.UserId && j.VenueInfoID == m.ID));
            }

            if (!string.IsNullOrWhiteSpace(request.Name))
            {
                queryable = queryable.Where(m => m.VI_Name.Contains(request.Name));
            }

            if (!string.IsNullOrWhiteSpace(request.PhoneNo))
            {
                queryable = queryable.Where(m => m.Vl_CellNum.Contains(request.PhoneNo));
            }

            if (request.ProvinceId.HasValue)
            {
                queryable = queryable.Where(m => m.ProvinceID == request.ProvinceId.Value);
            }

            if (request.CityId.HasValue)
            {
                queryable = queryable.Where(m => m.CityID == request.CityId.Value);
            }

            return queryable;
        }

        /// <summary>
        /// 获取场馆场地可用数最多营业配置列表
        /// </summary>
        private async Task<List<BusinessHoursConfig>> GetMaxBusinessHourConfigListAsync(List<Guid> siteIdList, bool isWork)
        {
            var queryable = _buinessHoursConfigRepository.AsNoTracking().Where(m => siteIdList.Contains(m.SiteInfoID));
            queryable = isWork ? queryable.Where(m => m.WorkDayCanUse) : queryable.Where(m => m.VacaDayCanUse);
            var a = await queryable.GroupBy(m => m.SiteInfoID).OrderByDescending(m => m.Count()).Select(m => new { SiteId = m.Key, Count = m.Count() }).FirstOrDefaultAsync();
            if (a != null)
            {
                var list = await _buinessHoursConfigRepository.AsNoTracking()
                    .Where(m => m.SiteInfoID == a.SiteId).OrderBy(m => m.TimeSlotBegin).ToListAsync();
                return list;
            }

            return new List<BusinessHoursConfig>();
        }
    }
}
